
package com.jsu.clubmanagementsystem.controller.file;

import com.jsu.clubmanagementsystem.common.BaseResponse;
import com.jsu.clubmanagementsystem.common.ResultUtils;
import com.jsu.clubmanagementsystem.model.entity.User;
import com.jsu.clubmanagementsystem.service.user.UserService;
import com.jsu.clubmanagementsystem.utils.MinIOUtil;
import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;

@RestController
public class UploadController {

    @Autowired
    private UserService userService;

    @Value("${file.access-url}")
    private String accessUrl;

    // 强制写死 photo 文件夹路径
    private String uploadPath;

    @PostConstruct
    public void initPath() {
        // 项目根路径 + photo
        uploadPath = System.getProperty("user.dir") + File.separator + "photo" + File.separator;
        File dir = new File(uploadPath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
    }

    @PostMapping("/upload-avatar")
    public BaseResponse<String> uploadAvatar(@RequestParam("file") MultipartFile file, @RequestParam Long userId) {
        if (file.isEmpty()) {
            return ResultUtils.error(400, "文件不能为空");
        }

        String contentType = file.getContentType();
        if (contentType == null || !contentType.startsWith("image/")) {
            return ResultUtils.error(400, "只能上传图片类型文件");
        }

        try {
            String avatarUrl = MinIOUtil.uploadFile("club", file);
            //  更新数据库中的用户头像字段
            User user = new User();
            user.setId(userId);
            user.setUserAvatar(avatarUrl);
            userService.updateById(user);
            return ResultUtils.success(avatarUrl);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtils.error(500, "文件保存失败");
        }
    }
}
